package db

import (
	"fmt"
	"translate_backend/AppConfig"

	"gopkg.in/mgo.v2"
)

var (

	// MongoSession stores mongo session
	mongoSession *mgo.Session

	// Mongo stores the mongodb connection string information
	mongoInfo *mgo.DialInfo

	// DBName mongodb的名称
	DBName string
)

// SessionStore 专门用来储存copy的session
type SessionStore struct {
	session *mgo.Session
}

// Connect connects to mongodb
func Connect() {

	//用户名和密码连接
	/*
	   dialInfo := &mgo.DialInfo{
	   	Addrs:     []string{"192.168.6.122"},
	   	Direct:    false,
	   	Timeout:   time.Second * 1,
	   	Database:  "yourdatabase",
	   	Source:    "admin",
	   	Username:  "username",
	   	Password:  "password",
	   	PoolLimit: 4096, // Session.SetPoolLimit
	   }
	   session, err := mgo.DialWithInfo(dialInfo)
	   if nil != err {
	   	panic(err)
	   }
	   defer session.Close()
	*/

	//从配置读取
	mdbName := AppConfig.Conf.MongoDB
	mdbHost := AppConfig.Conf.MongoHost
	mdbPort := AppConfig.Conf.MongoPort
	// mdbUser := AppConfig.Conf.MongoUser
	// mdbPass := AppConfig.Conf.MongoPass

	mongoDBUrl := "mongodb://" + mdbHost + ":" + mdbPort + "/" + mdbName // "mongodb://用户名:密码@localhost:27017/"
	//无用户名和密码的配置
	if mdbName == "" {
		//mongoDBUrl = "mongodb://192.168.110.233:27017/translate_app" // "mongodb://用户名:密码@localhost:27017/"
		mongoDBUrl = "mongodb://" + mdbHost + ":" + mdbPort + "/" + mdbName
	}

	fmt.Println("mongoDBUrl:", mongoDBUrl)

	mongo, err := mgo.ParseURL(mongoDBUrl)
	s, err := mgo.Dial(mongoDBUrl)

	if err != nil {
		fmt.Printf("Can't connect to mongo, go error %v\n", err)
		panic(err.Error())

		//数据库连接错误
		//return
	}

	s.SetMode(mgo.Monotonic, true) // 提高读性能,优先从副本读,不过这里只有一个实例
	s.SetSafe(&mgo.Safe{})         //安全模式,写操作强制数据库应答, 阻塞..
	fmt.Println("mongodb successed Connected to", mongoDBUrl)
	//defer s.Close()

	//建立索引
	//ensureIndex(s,mdbName)

	mongoSession = s
	mongoInfo = mongo
	DBName = mdbName

}

// NewSessionStore 为每一HTTP请求创建新的DataStore对象
func NewSessionStore() *SessionStore {
	ds := &SessionStore{
		session: mongoSession.Copy(),
	}
	return ds
}

// GetMgo 获取元session
func GetMgo() *mgo.Session {
	return mongoSession
}

// C 返回collection
func (d *SessionStore) C(name string) *mgo.Collection {
	return d.session.DB(DBName).C(name)
}

// Close 关闭session
func (d *SessionStore) Close() {
	d.session.Close()
}

// GetErrNotFound 返回错误表述
func GetErrNotFound() error {
	return mgo.ErrNotFound
}

// //建立索引
// func ensureIndex(s *mgo.Session,dbName string) {
//     session := s.Copy()
//     defer session.Close()

//     c := session.DB(dbName).C("langItem")

//     index := mgo.Index{
//         Key:        []string{"langkey"},
//         Unique:     true,
//         Background: true,
//         Sparse:     true,
//     }
//     err := c.EnsureIndex(index)
//     if err != nil {
// 		fmt.Printf("建立索引失败, error %v\n", err)
//         panic(err)
//     }
// }

//某个表的某个key建立唯一索引
/*
@s : mongo session
@dbName : 数据库名称
@collectionName : 表名
@key : 针对哪个可以
*/
func EnsureUniqueIndex(s *mgo.Session, dbName string, collectionName string, key string) {
	session := s.Copy()
	defer session.Close()

	c := session.DB(dbName).C(collectionName)

	index := mgo.Index{
		Key:        []string{key},
		Unique:     true,
		Background: true,
		Sparse:     true,
	}
	err := c.EnsureIndex(index)
	if err != nil {
		fmt.Printf("建立索引失败, error %v\n", err)
		panic(err)
	}
}
